package cn.itcast.hiss.form.service.impl;

import cn.itcast.hiss.form.mapper.HissDynamicTableMapper;
import cn.itcast.hiss.form.pojo.HissFormModel;
import cn.itcast.hiss.form.pojo.HissFormTableFields;
import cn.itcast.hiss.form.pojo.HissFormTables;
import cn.itcast.hiss.form.service.DynamicTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class DynamicTableServiceImpl implements DynamicTableService {

    @Autowired
    private HissDynamicTableMapper hissDynamicTableMapper;

    /**
     * 创建物理表和字段
     * @param hissFormModel
     * @param mainTables
     * @param fields
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPhysicalTable(HissFormModel hissFormModel, HissFormTables mainTables,List<HissFormTableFields> fields) {
        try {
            // 创建表
            hissDynamicTableMapper.createTable(hissFormModel, mainTables);
            // 创建表字段
            for (HissFormTableFields field : fields) {
                hissDynamicTableMapper.createField(mainTables, field);
            }
        }catch (Exception e){
            e.printStackTrace();
            // 手动删除创建的表
            hissDynamicTableMapper.dropTable(mainTables);
            throw new RuntimeException("创建物理表失败:"+mainTables.getTablePhysicalName(),e);
        }
    }

    /**
     * 字段
     * @param mainTables
     * @param fields
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPhysicalField(HissFormTables mainTables, List<HissFormTableFields> fields) {
        Set<String> success = new HashSet<>();
        try {
            for (HissFormTableFields field : fields) {
                hissDynamicTableMapper.createField(mainTables, field);
                success.add(field.getPhysicalName());
            }
        }catch (Exception e){
            e.printStackTrace();
            // 手动删除创建的字段
            for (String field : success) {
                hissDynamicTableMapper.dropField(mainTables,field);
            }
            throw new RuntimeException("创建物理字段失败:"+success,e);
        }
    }

}